<template>
  <div class="order-detail-container">
    <h2 class="page-title">订单详情</h2>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton style="width: 100%" :rows="10" animated />
    </div>
    
    <div v-else-if="orderInfo">
      <el-card class="order-info">
        <template #header>
          <div class="card-header">
            <span>订单信息</span>
            <el-tag :type="getOrderStatusType(orderInfo.status)">
              {{ orderInfo.statusDesc || getOrderStatusText(orderInfo.status) }}
            </el-tag>
          </div>
        </template>
        
        <div class="order-basic-info">
          <div class="info-item">
            <label>订单编号：</label>
            <span>{{ orderInfo.id }}</span>
          </div>
          <div class="info-item">
            <label>下单时间：</label>
            <span>{{ formatDateTime(orderInfo.createdAt) }}</span>
          </div>
          <div class="info-item" v-if="orderInfo.paidAt">
            <label>支付时间：</label>
            <span>{{ formatDateTime(orderInfo.paidAt) }}</span>
          </div>
          <div class="info-item">
            <label>订单金额：</label>
            <span class="price">¥ {{ orderInfo.totalPrice }}</span>
          </div>
          <div class="info-item" v-if="orderInfo.note">
            <label>备注：</label>
            <span>{{ orderInfo.note }}</span>
          </div>
        </div>
        
        <el-divider content-position="left">活动信息</el-divider>
        
        <div class="event-info">
          <div class="info-item">
            <label>活动名称：</label>
            <span>{{ orderInfo.eventName }}</span>
          </div>
          <div class="info-item">
            <label>活动时间：</label>
            <span>{{ formatDateTime(orderInfo.eventStartTime) }}</span>
          </div>
          <div class="info-item">
            <label>活动地点：</label>
            <span>{{ orderInfo.eventLocation }}</span>
          </div>
          <div class="info-item">
            <label>票种ID：</label>
            <span>{{ orderInfo.ticketId }}</span>
          </div>
          <div class="info-item">
            <label>票种名称：</label>
            <span>{{ orderInfo.ticketName }}</span>
          </div>
          <div class="info-item">
            <label>票价：</label>
            <span class="price">¥ {{ orderInfo.ticketPrice }}</span>
          </div>
        </div>
        
        <el-divider content-position="left">联系人信息</el-divider>
        
        <div class="contact-info">
          <div class="info-item">
            <label>联系人：</label>
            <span>{{ orderInfo.realName }}</span>
          </div>
          <div class="info-item">
            <label>手机号：</label>
            <span>{{ orderInfo.phone }}</span>
          </div>
          <div class="info-item">
            <label>邮箱：</label>
            <span>{{ orderInfo.contactEmail || '未提供' }}</span>
          </div>
          <div class="info-item">
            <label>地址：</label>
            <span>{{ orderInfo.address || '未提供' }}</span>
          </div>
          <div class="info-item">
            <label>邮编：</label>
            <span>{{ orderInfo.zipCode || '未提供' }}</span>
          </div>
          <div class="info-item">
            <label>出生日期：</label>
            <span>{{ formatDateTime(orderInfo.birthDate) }}</span>
          </div>
          <div class="info-item">
            <label>国家：</label>
            <span>{{ orderInfo.country || '未提供' }}</span>
          </div>
        </div>
        
        <el-divider content-position="left">订单内容</el-divider>
        
        <div class="order-items">
          <el-table :data="[{
            eventId: orderInfo.eventId,
            ticketId: orderInfo.ticketId,
            ticketName: orderInfo.ticketName,
            price: orderInfo.ticketPrice,
            quantity: orderInfo.quantity,
            subtotal: orderInfo.totalPrice
          }]" border stripe>
            <el-table-column label="票种ID" prop="ticketId" width="100" />
            <el-table-column label="票种名称" prop="ticketName" min-width="150" />
            <el-table-column label="单价" prop="price" width="120">
              <template #default="scope">
                <span class="price">¥ {{ Number(scope.row.price).toFixed(2) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="数量" prop="quantity" width="80" />
            <el-table-column label="小计" prop="subtotal" width="120">
              <template #default="scope">
                <span class="subtotal">¥ {{ Number(scope.row.subtotal).toFixed(2) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <el-divider content-position="left">电子票</el-divider>
        
        <div class="tickets-info">
          <template v-if="orderInfo.status === 'paid' && orderInfo.tickets && orderInfo.tickets.length > 0">
            <div class="ticket-list">
              <el-table :data="orderInfo.tickets" border stripe>
                <el-table-column label="票券编号" prop="ticketCode" />
                <el-table-column label="票种" prop="ticketTypeName" />
                <el-table-column label="价格" prop="price">
                  <template #default="scope">
                    <span class="price">¥ {{ (scope.row.price / 100).toFixed(2) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="活动时间" width="180">
                  <template #default="scope">
                    {{ formatDateTime(scope.row.eventStartTime) }}
                  </template>
                </el-table-column>
                <el-table-column label="活动地点" prop="eventVenue" />
                <el-table-column label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="getTicketStatusType(scope.row.status)">
                      {{ getTicketStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                  <template #default="scope">
                    <el-button size="small" @click="viewTicketDetail(scope.row.id)">查看详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
          <template v-else>
            <el-empty description="暂无电子票信息" />
          </template>
        </div>
        
        <div class="order-actions" v-if="orderInfo.status === 'unpaid'">
          <el-button type="primary" @click="goToPay">去支付</el-button>
          <el-button type="danger" @click="cancelOrder">取消订单</el-button>
        </div>
      </el-card>
    </div>
    
    <div v-else class="no-order">
      <el-empty description="未找到订单信息" />
    </div>
    
    <div class="back-button">
      <el-button @click="goBack">返回列表</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrderDetail } from '@/api/order'

const route = useRoute()
const router = useRouter()
const orderId = route.query.id

// 订单信息
const orderInfo = ref(null)
// 加载状态
const loading = ref(true)

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '未提供';
  
  // 如果包含T，说明是带时间的日期格式
  if (dateTimeStr.includes('T')) {
    return dateTimeStr.replace('T', ' ').substring(0, 19);
  }
  
  return dateTimeStr;
}

// 获取订单详情
const fetchOrderDetail = async () => {
  if (!orderId) {
    ElMessage.error('未指定订单ID')
    router.push('/front/user/orders')
    return
  }
  
  loading.value = true
  try {
    const res = await getOrderDetail(orderId)
    console.log('订单详情响应:', res)
    
    if (res.code === 200 && res.data) {
      orderInfo.value = res.data
      console.log('处理后的订单详情:', orderInfo.value)
    } else {
      ElMessage.error('获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情出错:', error)
    ElMessage.error('获取订单详情失败')
  } finally {
    loading.value = false
  }
}

// 获取订单状态类型
const getOrderStatusType = (status) => {
  switch (status) {
    case 'paid': return 'success'
    case 'unpaid': return 'warning'
    case 'cancelled': return 'danger'
    default: return 'info'
  }
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  switch (status) {
    case 'paid': return '已支付'
    case 'unpaid': return '待支付'
    case 'cancelled': return '已取消'
    default: return '未知状态'
  }
}

// 获取电子票状态类型
const getTicketStatusType = (status) => {
  switch (status) {
    case 0: return 'info' // 未使用
    case 1: return 'success' // 已使用
    case 3: return 'danger' // 已取消
    default: return 'info'
  }
}

// 获取电子票状态文本
const getTicketStatusText = (status) => {
  switch (status) {
    case 0: return '未使用'
    case 1: return '已使用'
    case 3: return '已取消'
    default: return '未知状态'
  }
}

// 查看电子票详情
const viewTicketDetail = (ticketId) => {
  router.push({
    path: '/front/user/ticket-detail',
    query: { id: ticketId }
  })
}

// 去支付
const goToPay = () => {
  router.push({
    path: '/front/order/pay',
    query: { orderId }
  })
}

// 取消订单
const cancelOrder = async () => {
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？取消后不可恢复', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    ElMessage.success('订单已取消')
    // 刷新订单详情
    fetchOrderDetail()
  } catch (error) {
    console.log('用户取消操作')
  }
}

// 返回列表
const goBack = () => {
  router.push('/front/user/orders')
}

// 页面加载时获取数据
onMounted(() => {
  fetchOrderDetail()
})
</script>

<style scoped>
.order-detail-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  color: #303133;
}

.loading-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-basic-info, .contact-info, .event-info {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  line-height: 24px;
  margin-bottom: 5px;
}

.info-item label {
  color: #606266;
  width: 90px;
  text-align: right;
  margin-right: 10px;
  font-weight: 500;
}

.order-items, .ticket-list {
  margin-bottom: 30px;
}

.price, .subtotal {
  color: #f56c6c;
  font-weight: bold;
}

.no-order {
  text-align: center;
  padding: 50px 0;
}

.order-actions {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.back-button {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* Add some section styling */
.el-divider {
  margin: 24px 0;
}

.el-divider__text {
  font-size: 16px;
  font-weight: 500;
  color: #409EFF;
}
</style> 